<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片组件 -->
    <el-card class="box-card">
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="removeRole(scope.row, item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="8">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRole(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="16">
                    <el-tag
                      type="danger"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRole(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色管理"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div>
              <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRolesRight(scope.row)">分配权限</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addRoleClose">
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolePow">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="setRolesDialogVisible" width="50%" @close="setRoleReset">
      <!-- 树形控件 -->
      <el-tree :data="roleRightList" :props="TreeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="rightsArr" ref="tree"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data () {
    return {
      rolesList: [],
      // 添加角色对话框是否开启
      addDialogVisible: false,
      // 添加角色信息
      addRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色验证规则
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名称的长度在2~10个字符之间', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 15, message: '角色描述的长度在2~15个字符之间', trigger: 'blur' }
        ]
      },
      // 控制是否开启分配权限对话框
      setRolesDialogVisible: false,
      // 所有权限列表
      roleRightList: [],
      // 树形控件数据
      TreeProps: {
        label: 'authName',
        children: 'children'
      },
      // 权限管理对话框中默认选中的权限列表数据
      rightsArr: [],
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取权限列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.rolesList = res.data
    },
    // 删除某个权限
    async removeRole (role, rightId) {
      const confimMsg = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confimMsg !== 'confirm') return this.$msg.info('已取消删除')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)

      role.children = res.data
    },
    // 添加角色
    addRole () {
      this.addDialogVisible = true
    },
    // 取消添加用户对话框时,重置规则
    addRoleClose (val) {
      this.$refs.addRuleFormRef.resetFields()
    },
    // 添加用户
    async addRolePow () {
      const { data: res } = await this.$http.post('roles', this.addRuleForm)
      if (res.meta.status !== 201) return this.$msg.error(res.meta.msg)
      this.addDialogVisible = false
      this.getRolesList()
    },
    // 分配权限
    async setRolesRight (roles) {
      this.roleId = roles.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)

      this.roleRightList = res.data

      this.getKeys(roles, this.rightsArr)
      this.setRolesDialogVisible = true
    },
    // 使用递归获取三级权限的 id
    // node 是指对那个数组进行查找处理
    // arr 是一个数组,是指将最终处理的结果放到哪个地方
    getKeys (node, arr) {
      // 首先需要了解: 第三节的权限是没有children属性的

      // 判断传入过来的节点是否有children属性
      // 如果没有,说明是第三级的权限,直接获取返回即可
      if (!node.children) {
        return arr.push(node.id)
      }

      // 如果有children属性,说明不是三级权限
      // children是一个数组,这时候调用forEach方法,对children进行遍历
      // 将每一个传入getKeys方法,进行处理,然后对数据继续解析判断
      node.children.forEach(item => {
        this.getKeys(item, arr)
      })
    },
    // 重置权限管理对话框节点 ID 值
    setRoleReset () {
      this.rightsArr = []
    },
    async allotRights () {
      var rightIdArr = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ]
      const idStr = rightIdArr.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.$msg.success(res.meta.msg)
      this.getRolesList()
      this.setRolesDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
